package cn.yuanqiao.archive.storeRoom.service.impl;

import cn.yuanqiao.archive.storeRoom.mapper.InitializationMapper;
import cn.yuanqiao.archive.storeRoom.service.InitializationService;
import cn.yuanqiao.common.domain.YqField;
import cn.yuanqiao.common.domain.YqTable;
import cn.yuanqiao.common.enums.DbIdEnum;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.config.YqDatabaseIdProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class InitializationServiceImpl implements InitializationService {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private InitializationMapper initializationMapper;
    @Resource
    private YqDatabaseIdProvider yqDatabaseIdProvider;
    @Override
    public  void initializationTable() {
        String databaseId =  yqDatabaseIdProvider.getDatabaseId();
        try {
            String tenantCode = SecurityUtils.getTenantCode();

            //首先获取该连接所有的表  然后如果没有那么创建
            List<String> tables = new ArrayList<>();
            if(databaseId.equalsIgnoreCase(DbIdEnum.MYSQL.getCode())){
                tables=initializationMapper.getAllTablesList(tenantCode.toUpperCase());
            }else {
                String tablesStr=initializationMapper.getAllTables(tenantCode.toUpperCase());
                if(!"".equals(tablesStr)&&tablesStr!=null){
                    tables=Arrays.asList(tablesStr.toUpperCase().split(","));
                }
            }
            //获取yqtable表里的所有数据
            List<YqTable> tableList = initializationMapper.getTableList();
            String sql = "";
            for (YqTable yqTable : tableList) {
                String tableName=yqTable.getTableName();
                if(StringUtils.isEmpty(tenantCode)){
                    throw new ServiceException("TenantCode is null");
                }else{
                    tableName=tenantCode.toUpperCase()+"_"+tableName;
                }
                if (tables.contains(tableName.toUpperCase())|| tables.contains(tableName.toLowerCase())) {
                    //if (tables.contains(yqTable.getTableName().toUpperCase())) {
                    //如果包含只需要判断是否含有该字段，如果含有的话那么就不管没有的话就新增
                    String sqluser = initializationMapper.getSqlUser();
                    List<YqField> fieldList = initializationMapper.getFields(yqTable.getTableId());
                    // List<String> filesList = Arrays.asList(initializationMapper.getFieldList(yqTable.getTableName()+"_"+tenantCode.toUpperCase(), sqluser).toUpperCase().split(","));
                    List<String> filesList = Arrays.asList(initializationMapper.getFieldList(tableName, sqluser).toUpperCase().split(","));

                    for (YqField yqField : fieldList) {
                        if (!filesList.contains(yqField.getFieldName().toUpperCase())) {
                            int fieldLength = yqField.getFieldLength();
                            int fieldtype = yqField.getFieldType();
                            String fieldTypeString = "";
                            if (fieldtype == 1) {//判断字段类型
                                if (fieldLength > 10) {
                                    fieldTypeString = "BIGINT";
                                } else {
                                    fieldTypeString = "INTEGER";
                                }
                            } else if (fieldtype == 2) {
                                fieldTypeString = "DOUBLE";
                            } else if (fieldtype == 3) {
                                fieldTypeString = "VARCHAR";
                            } else if (fieldtype == 4) {
                                fieldTypeString = "BYTE";
                            } else if (fieldtype == 5) {
                                fieldTypeString = "DATE";
                            } else if (fieldtype == 6) {
                                fieldTypeString = "TIMESTAMP(0)";
                            } else if (fieldtype == 7) {
                                fieldTypeString = "BIT";
                            } else if (fieldtype == 8) {
                                fieldTypeString = "TEXT";
                            }else if (fieldtype == 9) {
                                if(databaseId.equalsIgnoreCase(DbIdEnum.HIGHGO.getCode())) {
                                    fieldTypeString = "TEXT";
                                }else{
                                    fieldTypeString = "CLOB";

                                }
                            }
                            String alterSql = "ALTER TABLE " + tableName + " ADD " + yqField.getFieldName() + " " + fieldTypeString;
                            if (fieldtype == 3) {
                                alterSql += "(" + fieldLength + ")";
                            }
                            if ("0".equals(yqField.getNULLABLE())) {
                                //1可以为空 0不可以为空
                                alterSql += " NOT NULL";
                            }

                            initializationMapper.createTable(alterSql);

                        }

                    }

                } else {
                    //创建表
                    List<YqField> fieldList = initializationMapper.getFields(yqTable.getTableId());
                    String bepk = "";
                    //  sql = "CREATE TABLE " + yqTable.getTableName()+"_"+tenantCode.toUpperCase() + "(";
                    if(fieldList.size()>0) {
                        sql = "CREATE TABLE " + tableName + "(";
                        for (int i = 0; i < fieldList.size(); i++) {
                            YqField yqField = fieldList.get(i);
                            String isEmpty = yqField.getNULLABLE();
                            int fieldtype = yqField.getFieldType();
                            String fieldTypeString = "";
                            String NoEmpty = "";
                            if ("0".equals(isEmpty)) {
                                //1可以为空 0不可以为空
                                NoEmpty = "NOT NULL";
                            }

                            if (yqField.getBEPK() == 1) {
                                bepk = yqField.getFieldName();
                            }
                            int fieldLength = yqField.getFieldLength();
                            if (fieldtype == 1) {//判断字段类型
                                if (fieldLength > 10) {
                                    fieldTypeString = "BIGINT";
                                } else {
                                    fieldTypeString = "INTEGER";
                                }
                            } else if (fieldtype == 2) {
                                fieldTypeString = "DOUBLE";
                            } else if (fieldtype == 3) {
                                fieldTypeString = "VARCHAR";
                            } else if (fieldtype == 4) {
                                fieldTypeString = "BYTE";
                            } else if (fieldtype == 5) {
                                fieldTypeString = "DATE";
                            } else if (fieldtype == 6) {
                                fieldTypeString = "TIMESTAMP(0)";
                            } else if (fieldtype == 7) {
                                fieldTypeString = "BIT";
                            } else if (fieldtype == 8) {
                                fieldTypeString = "TEXT";
                            } else if (fieldtype == 9) {
                                if(databaseId.equalsIgnoreCase(DbIdEnum.HIGHGO.getCode())) {
                                    fieldTypeString = "TEXT";
                                }else if(databaseId.equalsIgnoreCase(DbIdEnum.MYSQL.getCode())){
                                    fieldTypeString = "TEXT";
                                }else{
                                    fieldTypeString = "CLOB";

                                }
                            }
                            if (i == 0) {
                                sql += " " + yqField.getFieldName() + " " + fieldTypeString;
                            } else {
                                sql += "," + yqField.getFieldName() + " " + fieldTypeString;
                            }
                            if (fieldtype == 3) {
                                sql += "(" + fieldLength + ") ";
                            }
                            sql += " " + NoEmpty;
                        }
                        if (StringUtils.isEmpty(bepk)) {
                            sql += ")";
                        } else {
                            if(databaseId.equalsIgnoreCase(DbIdEnum.OSCAR.getCode())){
                                sql += ",CONSTRAINT TBL_" + tableName + "_PKEY PRIMARY KEY (" + bepk + ") );";
                            }else if(databaseId.equalsIgnoreCase(DbIdEnum.HIGHGO.getCode())){
                                sql += ",CONSTRAINT TBL_" + tableName + "_PKEY PRIMARY KEY (" + bepk + ") );";
                            }else if(databaseId.equalsIgnoreCase(DbIdEnum.KINGBASE.getCode())){
                                sql += ",CONSTRAINT TBL_" + tableName + "_PKEY PRIMARY KEY (" + bepk + ") );";
                            }else if(databaseId.equalsIgnoreCase(DbIdEnum.MYSQL.getCode())){
                                sql += ",PRIMARY KEY (`" + bepk + "`) USING BTREE );";
                            }else{
                                sql += ",CONSTRAINT " + tableName + "_PK NOT CLUSTER  PRIMARY KEY (" + bepk + ") );";
                            }
                        }
                        initializationMapper.createTable(sql);
                    }

                }


            }

        }catch (Exception ex){
            logger.error(ex.getMessage(),ex);
            throw new ServiceException("创建表失败"+ex.getMessage());
        }



    }

    @Override
    public List<YqTable> getTableList() {
        return initializationMapper.getTableList();
    }

    @Override
    public List<YqField> getFieldList(String tableId) {
        return initializationMapper.getFieldListByTableId(tableId);
    }

    @Override
    public int insertYqtable(String tableName, String tableCaption, String description, int type) {
        return initializationMapper.insertYqtable(tableName,tableCaption,description,type);
    }


}
